// 获取 tbody 标签
const oTbody = document.querySelector('tbody')
// 获取 div
const oDiv = document.querySelector('.bigbox')
// 获取添加弹窗
const oAdd = document.querySelector('.add')
// 获取编辑弹窗
const oChange = document.querySelector('.change')
// 定义变量存储点击的数据的索引下标
let index

// 定义变量存储json文件
let arr
setPage()
// 渲染函数
async function setPage() {
  const res = JSON.parse(await myPromiseAjax({
    type: 'get',
    url: '/api/getTable'
  }))
  arr = res
  console.log(res)
  let str = ``
  res.forEach((item, index) => {
    str += `
    <tr>
      <td>${item.id}</td>
      <td>${item.name}</td>
      <td>${item.tel}</td>
      <td>${item.email}</td>
      <td>
        <p class="${item.sex === '男' ? 'nan' : 'nv'}">${item.sex}</p>
      </td>
      <td>
        <p class="${item.state === 'true' ? 'avail' : 'dis'}">${item.state === 'true' ? '可用' : '禁用'}</p>
      </td>
      <td>
        <button index="${index}" class="changeBtn">编辑</button>
        <button index="${index}" class="delBtn">删除</button>
      </td>
    </tr>
    `
  })
  oTbody.innerHTML = str
}
// 给div添加点击事件委托
oDiv.addEventListener('click', e => {
  // 点击添加
  if (e.target.className === 'addBtn') {
    oAdd.style.display = 'flex'
  }
  // 点击编辑
  else if (e.target.className === 'changeBtn') {
    oChange.style.display = 'flex'
    // 将对应的数据渲染到编辑页面
    index = Number(e.target.getAttribute('index'))
    oChange.querySelector('[name = name]').value = arr[index].name
    oChange.querySelector('[name = email]').value = arr[index].email
    oChange.querySelector('[name = tel]').value = arr[index].tel
    oChange.querySelectorAll('[name = sex').forEach(item => {
      if (item.value === arr[index].sex) {
        item.checked = true
        console.log(item.value)
        console.log(arr[index].sex)
      }
    })
  }
  // 点击删除
  else if (e.target.className === 'delBtn') {

    if (window.confirm('您确定删除该信息吗?')) {
      // 调用发送请求
      arr.splice(Number(e.target.getAttribute('index')), 1)
      sendRequest('post', '/api/setTable', arr)
      setPage()
      popup.msg("删除成功")
    }

  }
})


// 给增加div添加点击事件委托
oAdd.addEventListener('click', e => {
  // 点击×或者取消按钮
  if (e.target.className === 'false') {
    oAdd.style.display = 'none'
    // 点击确认按钮
  } else if (e.target.className === 'true') {
    // 获取需要添加的信息
    let name = oAdd.querySelector('[name = name]').value
    let password = oAdd.querySelector('[name = password]').value
    let email = oAdd.querySelector('[name = email]').value
    let sex
    oAdd.querySelectorAll('[name = sex').forEach(item => {
      if (item.checked) {
        sex = item.value
      }
    })
    let tel = oAdd.querySelector('[name = tel]').value

    let obj = {
      id: arr.length === 0 ? 1 : arr[arr.length - 1].id + 1,
      name: name,
      password: password,
      tel: tel,
      email: email,
      sex: sex,
      state: "false"
    }
    // 调用发送请求
    arr.push(obj)
    sendRequest('post', '/api/setTable', arr)
    setPage()
    oAdd.style.display = 'none'
  popup.msg("添加成功")

  }
})

// 给编辑div添加点击事件委托
oChange.addEventListener('click', e => {
  if (e.target.className === 'false') {
    oChange.style.display = 'none'
  } else if (e.target.className === 'true') {
    // 获取需要添加的信息
    let name = oChange.querySelector('[name = name]').value
    let password = oChange.querySelector('[name = password]').value
    let email = oChange.querySelector('[name = email]').value
    let sex
    oChange.querySelectorAll('[name = sex').forEach(item => {
      if (item.checked) {
        sex = item.value
      }
    })
    let tel = oChange.querySelector('[name = tel]').value

    arr[index] = {
      id: arr[index].id,
      name: name,
      password: password,
      tel: tel,
      email: email,
      sex: sex,
      state: arr[index].state
    }
    // 调用发送请求
    sendRequest('post', '/api/setTable', arr)
    setPage()
    oChange.style.display = 'none'
  }
})


// 发送请求函数
async function sendRequest(type, url, data) {
  if (type === 'get') {
    return JSON.parse(await myPromiseAjax({
      type: type,
      url: url
    }))
  } else if (type === 'post') {
    return JSON.parse(await myPromiseAjax({
      type: type,
      url: url,
      data: JSON.stringify(data)
    }))
  }

}



// 弹出层
window.popup = window.Popup = (function (window) {
  class Popup {
    constructor() {
    }
    confirm(text, cb = () => { }) {
      this.msgPrepare(text)
      this.box.style.height = '15%'
      let yesBtn = document.createElement('span')
      yesBtn.innerText = '确定'
      this.setStyle(yesBtn, {
        'position': 'absolute',
        'right': '70px',
        'bottom': '10px',
        'background-color': '#0ff',
        'color': '#fff',
        'border-radius': '2px',
        'padding': '2px 5px'
      })
      this.box.appendChild(yesBtn)

      let noBtn = document.createElement('span')
      noBtn.innerText = '取消'
      this.setStyle(noBtn, {
        'position': 'absolute',
        'right': '10px',
        'bottom': '10px',
        'background-color': '#f00',
        'color': '#fff',
        'border-radius': '2px',
        'padding': '2px 5px'
      })
      this.box.appendChild(noBtn)

      noBtn.onclick = e => this.close()
      yesBtn.onclick = e => {
        cb()
      }
    }
    close() {
      this.box.parentElement.removeChild(this.box)
    }
    msg(text, cb) {
      this.msgPrepare(text)
      setTimeout(() => {
        this.box.parentElement.removeChild(this.box)
        cb && cb()
      }, 2000)
    }
    msgPrepare(text) {
      this.box = document.createElement('div')
      this.box.innerText = text
      this.setStyle(this.box, {
        width: '50%',
        backgroundColor: 'rgba(255,255,0,.7)',
        color: '#f00',
        borderRadius: '4px',
        position: 'absolute',
        left: '50%',
        transform: 'translate(-50%,-50%)',
        padding: '10px',
        fontWeight: 'bold'
      })
      document.body.appendChild(this.box)
      let t = this.box.offsetHeight
      let maxT = document.documentElement.clientHeight / 2
      this.box.style.top = t + 'px'
      let timer = setInterval(() => {
        t += 10
        if (t >= maxT) {
          t = maxT
          clearInterval(timer)
        }
        this.box.style.top = t + 'px'
      }, 20)
    }
    setStyle(ele, styleObj) {
      for (var key in styleObj) {
        ele.style[key] = styleObj[key]
      }
    }
  }
  var popup
  return (function (window) {
    if (!popup) popup = new Popup
    return popup
  })(window)
})(window)